package controllers.Account;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import util.GoEasyUtil;
import controllers.item.LoginDisplay;
import controllers.session.LoginSession_WebSocketSession;
import core.dao.LoginDisplayService;
import core.login.LoginSession_WebSocketSessionInterface;

@Controller
@RequestMapping("/login")
public class LoginController {
	private static final Logger logger = Logger
			.getLogger(LoginController.class);
	@Resource(name = "goEasyUtil")
	private GoEasyUtil goEasyUtil;

	// @Resource(name = "loginSession_WebSocketSession")
	private LoginSession_WebSocketSessionInterface loginSession_WebSocketSessionInterface = LoginSession_WebSocketSession
			.getSession();

	@Resource(name = "loginDisplayServiceImpl")
	private LoginDisplayService loginDisplayServiceImpl;

	@RequestMapping("loginPage")
	public String loginPage(HttpServletRequest request) {
		logger.info("msgtest");
		// logger.debug("");
		// logger.warn("");
		// logger.error("");
		return "login/login";
	}

	// @ResponseBody
	// @RequestMapping(value = "login", method = RequestMethod.POST)
	// public LoginDisplay login(HttpServletRequest request,
	// @RequestBody LoginDisplay loginDisplay) throws Exception {
	// // 登录成功将用户的id md5码作为url{key}
	// LoginDisplay login = loginDisplayServiceImpl.getLogin(
	// loginDisplay.getNickName(), loginDisplay.getPassWord());
	// if (login != null) {
	// System.out.println(login.getEncryptionId());
	//
	// System.out.println(login.DecryptByDisplay());
	// checkOldSess_saveNewSess(login, request);
	// // 登录成功后设置登陆session和key
	// request.getSession().setAttribute("login", login);
	// request.setAttribute("key", login.getEncryptionId());
	// }
	// return login;
	// }
	// 表单提交无需使用requestBody 如果使用则会报451错
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(HttpServletRequest request, LoginDisplay loginDisplay)
			throws Exception {
		// 登录成功将用户的id md5码作为url{key}
		LoginDisplay login = loginDisplayServiceImpl.getLogin(
				loginDisplay.getNickName(), loginDisplay.getPassWord());
		
//		MDC.put("n", "login");
		logger.info("test");
	
		if (login != null) {
			checkOldSess_saveNewSess(login, request);
			// 登陆成功则存放此时登陆的sesionID=session

			request.setAttribute("sid", request.getSession().getId());
			request.setAttribute("lid", login.getEncryptionId());
			request.getSession().setAttribute("login", login);
			return "play/play";
		}

		return "login/login";
	}

	// @RequestMapping(value = "/person/login", method = RequestMethod.POST)
	// public @ResponseBody
	// User login(@RequestBody User person) {
	// return person;
	// }
	@ResponseBody
	@RequestMapping(value = "login2", method = RequestMethod.POST)
	public String login2(HttpServletRequest request,
			@RequestBody LoginDisplay loginDisplay) {
		return "test";
	}

	/**
	 * 检查是否登录过如果登陆过则对旧的session设置提示有重复登陆
	 * 
	 * @param login
	 * @param request
	 */
	private void checkOldSess_saveNewSess(LoginDisplay login,
			HttpServletRequest request) {

		HttpSession oldLoginSession = loginSession_WebSocketSessionInterface
				.getHttpSessionByLid(login.DecryptByDisplay());
		// oldLoginSession不为null则重复登录
		if (oldLoginSession != null) {
			System.out.println(request.getSession().getId() + " old:"
					+ oldLoginSession.getId());
			// 如果浏览器已经有账号登录成功但是去登录页面重新登录自己账号会生成新的sessionID则这里判断不了session是否为同一个
			if (oldLoginSession.getId() == request.getSession().getId()) {

				request.setAttribute("LoginMsg", "您已经登陆,无需重复登陆");
				return;
			} else {
				// login.setMsg1("您已经登陆,无需重复登陆");
				if (oldLoginSession.getAttribute("login") != null) {
					try {
						// WebSocketUtil.httpSessionId_webSocket
						// .get(oldLoginSession.getId()).getBasicRemote()
						// .sendText("1");
						Session webSocketSession = loginSession_WebSocketSessionInterface
								.getWebSocketSessionByLid(login
										.DecryptByDisplay());
						if (webSocketSession != null) {
							webSocketSession.getBasicRemote().sendText("1");
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
					/**
					 * session销毁监听器执行移除集合session主要移除sid—
					 * sessionMap因为每个sessionId不一致所以无法用put顶替掉原来的但lid是唯一的则可以
					 */
					oldLoginSession.invalidate();
					if (loginSession_WebSocketSessionInterface
							.getWebSocketSessionByLid(login.DecryptByDisplay()) != null) {
						try {
							loginSession_WebSocketSessionInterface
									.getWebSocketSessionByLid(
											login.DecryptByDisplay()).close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

					// loginSession_WebSocketSessionInterface
					// .removeLoginSession_WebSocketSession(loginSession_WebSocketSessionInterface
					// .getLoginIdBySession(oldLoginSession));
				}
				// 登录成功后设置登陆session和key
				// session销毁时间
				// request.getSession().setMaxInactiveInterval(20);

				// LoginSessionMap.LOGIN_SESSION.put(login.DecryptByDisplay(),
				// request.getSession());
				// LoginSessionMap.SESSIONID_SESSION.put(request.getSession().getId(),
				// request.getSession());

			}
		}
		loginSession_WebSocketSessionInterface.saveLoginSession(
				login.DecryptByDisplay(), request.getSession());
	}
}